package com.pzhuweb.sgblog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pzhuweb.sgblog.domain.entity.LoginUser;
import com.pzhuweb.sgblog.domain.entity.User;
import com.pzhuweb.sgblog.mapper.UserMapper;
import com.pzhuweb.sgblog.service.BlogLoginService;
import com.pzhuweb.sgblog.domain.utils.BeanCopyUtils;
import com.pzhuweb.sgblog.domain.utils.JwtUtil;
import com.pzhuweb.sgblog.domain.utils.RedisCache;
import com.pzhuweb.sgblog.domain.utils.ResponseResult;
import com.pzhuweb.sgblog.domain.vo.BlogUserLoginVo;
import com.pzhuweb.sgblog.domain.vo.UserInfoVo;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author 鄧浩奇
 * @Classname BlogLoginServiceImpl
 * @Description
 * @Date 2023/5/11 19:01
 **/

@Service
public class BlogLoginServiceImpl extends ServiceImpl<UserMapper,User> implements BlogLoginService {

    @Resource
    private RedisCache redisCache;

    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public ResponseResult<User> login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 判断认证是否通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");//
        }
        // 不为空，获取userID生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userID = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userID);
        // 把用户信息存入Redis
        redisCache.setCacheObject("blogLogin："+userID,loginUser);
        // 把token和userinfo封装返回
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        BlogUserLoginVo blogUserLoginVo = new BlogUserLoginVo(jwt,userInfoVo);
        return ResponseResult.okResult(blogUserLoginVo);
    }

    @Override
    public ResponseResult logout() {
        // 获取token
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //解析token，获取userID
        Long id = loginUser.getUser().getId();
        // 组合redis的key，根据key删除redis中的用户信息
        String key = "blogLogin："+id.toString();
        redisCache.deleteObject(key);
        return ResponseResult.okResult();
    }
}
